package com.jy.adscm.operation.mscyb.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.operation.aftersales.bean.ShylMaterial;
import com.jy.adscm.operation.aftersales.mapper.mysql.ShylMaterialMapper;
import com.jy.adscm.operation.base.bean.JyGoods;
import com.jy.adscm.operation.base.mapper.mysql.JyGoodsMapper;
import com.jy.adscm.operation.cg.bean.*;
import com.jy.adscm.operation.cg.mapper.mysql.*;
import com.jy.adscm.operation.cg.service.CgTaskService;
import com.jy.adscm.operation.cgxsb.bean.CgxsTaskinfo;
import com.jy.adscm.operation.cgxsb.mapper.mysql.BaseTaskdetailinfoMapper;
import com.jy.adscm.operation.cgxsb.mapper.mysql.CgxsCommodityinfoMapper;
import com.jy.adscm.operation.cgxsb.mapper.mysql.CgxsTaskinfoMapper;
import com.jy.adscm.operation.mscyb.bean.*;
import com.jy.adscm.operation.mscyb.mapper.mysql.*;
import com.jy.adscm.operation.mscyb.service.JqylMaterialService;
import com.jy.adscm.operation.mscyb.service.JqylMaterialdetailApproveService;
import com.jy.adscm.operation.mscyb.service.JqylMaterialdetailService;
import com.jy.adscm.operation.purchase.bean.Purchasebom;
import com.jy.adscm.operation.purchase.mapper.mysql.PurchasebomMapper;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.system.mapper.mysql.JyUserMapper;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.utils.AdscmDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyl
 * @since 2018-11-29
 */
@Service
public class JqylMaterialdetailServiceImpl extends ServiceImpl<JqylMaterialdetailMapper, JqylMaterialdetail> implements JqylMaterialdetailService {
    @Autowired
    JqylMaterialMapper  jqylMaterialMapper;


    @Autowired
    JyUserMapper jyUserMapper;
    @Autowired
    JqzzMaterialListCheckMapper jqzzMaterialListCheckMapper;
    @Autowired
    JqbzMaterialListCheckMapper jqbzMaterialListCheckMapper;
    @Autowired
    JqylMaterialdetailApproveService jqylMaterialdetailApproveService;
     @Autowired
     CgTaskService cgTaskService;
     @Autowired
    CgBomSupplierMapper cgBomSupplierMapper;
     @Autowired
     CgSupplierMapper cgSupplierMapper;
     @Autowired
    CgTaskDetailMapper cgTaskDetailMapper;
    @Autowired
    JqylMaterialService jqylMaterialService;
    @Autowired
    CgMaterialMapper cgMaterialMapper;
    @Autowired
    ShylMaterialMapper shylMaterialMapper;
    @Autowired
    CgTaskMapper cgTaskMapper;
    @Autowired
    JqylMaterialdetailRebackMapper jqylMaterialdetailRebackMapper;
    @Transactional
    @Override
    public Boolean updateLjzzPartsmadedetail(JqylMaterialdetail jqylMaterialdetail) {
        return super.updateById(jqylMaterialdetail);
    }

    @Override
    public List<JqylMaterialdetail> selectByTid(String tid) {
        Wrapper<JqylMaterialdetail>  wrapper =new EntityWrapper<>();
        wrapper.eq("TID",tid);
        List<JqylMaterialdetail> jqylMaterialdetails = super.selectList(wrapper);
        for (JqylMaterialdetail jqylMaterialdetail : jqylMaterialdetails) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterialdetail.getUseperson(),null)){
                JyUser jyUser = jyUserMapper.selectById(jqylMaterialdetail.getUseperson());
                jqylMaterialdetail.setUsepersonName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterialdetail.getName(),null)){
                CgMaterial cgMaterial = cgMaterialMapper.selectById(jqylMaterialdetail.getName());
                jqylMaterialdetail.setNameName(cgMaterial.getName());
            }
            DecimalFormat df=new DecimalFormat("#0.00");
            String format = df.format(jqylMaterialdetail.getUsenums());
            jqylMaterialdetail.setUsenums(Double.valueOf(format));
        }

        return jqylMaterialdetails;
    }

    @Override
    public List<JqylMaterialdetail> selectUnqualifiedMaterial() {
        Wrapper<JqylMaterialdetail> wrapper =new EntityWrapper<>();
        wrapper.eq("MATERIALSTATE",0);
        wrapper.orderBy("ISREPAIR",true);
        List<JqylMaterialdetail> jqylMaterialdetails = super.selectList(wrapper);
        for (JqylMaterialdetail jqylMaterialdetail : jqylMaterialdetails) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterialdetail.getUseperson(),null)){
                JyUser jyUser = jyUserMapper.selectById(jqylMaterialdetail.getUseperson());
                jqylMaterialdetail.setUsepersonName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterialdetail.getName(),null)){
                CgMaterial cgMaterial = cgMaterialMapper.selectById(jqylMaterialdetail.getName());
                jqylMaterialdetail.setNameName(cgMaterial.getName());
            }
            DecimalFormat df=new DecimalFormat("#0.00");
            String format = df.format(jqylMaterialdetail.getUsenums());
            jqylMaterialdetail.setUsenums(Double.valueOf(format));
        }
        return jqylMaterialdetails;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean insertJqylMaterialdetail(JqylMaterialdetail jqylMaterialdetail, Token token)throws AdscmSystemException {


        //查询是否物料已经入库
        JqylMaterial jqylMaterial = jqylMaterialMapper.selectById(jqylMaterialdetail.getTid());
        if (!AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterial,null)){
            throw  new AdscmSystemException("没找到任务书信息");
        }
         if (!"1".equals(jqylMaterial.getIstaskbegin())){
          throw  new AdscmSystemException("物料未入库，不能添加出库信息");
         }
         if (jqylMaterial.getRemainingnums()==0){
             throw  new AdscmSystemException("物料已经用完");
         }
          if (jqylMaterial.getRemainingnums()<jqylMaterialdetail.getUsenums()){
              throw new AdscmSystemException("使用量超过了剩余量");
          }
          //减去任务书中的剩余数量
        DecimalFormat df=new DecimalFormat("#0.0000");
        String format = df.format(jqylMaterial.getRemainingnums()-jqylMaterialdetail.getUsenums());

        jqylMaterial.setRemainingnums(Float.valueOf(format));
        jqylMaterialMapper.updateById(jqylMaterial);
        //根据任务书中的物料名称获取到物料的编码
        CgMaterial cgMaterial = cgMaterialMapper.selectById(jqylMaterial.getResourcename());
        //物料编码
        if (AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial.getCode(),null)){
            String productcode = cgMaterial.getCode();
            if (jqylMaterialdetail.getUsenums()>1){
                throw  new AdscmSystemException("添加数量大于1，不能生成对应条码");
            }
            String yearMonth = new SimpleDateFormat("yyMM").format(new Date());
            Wrapper<JqylMaterialdetail>  wrapper=new EntityWrapper<>();
            wrapper.like("CODE", productcode + yearMonth, SqlLike.RIGHT);
            wrapper.orderBy("CODE",false);
            List<JqylMaterialdetail> jqylMaterialdetails = super.selectList(wrapper);
            String code="";
            if (jqylMaterialdetails.size()>0){
                JqylMaterialdetail oldjqylMaterialdetail = jqylMaterialdetails.get(0);
                String oldCode = oldjqylMaterialdetail.getCode();
                Integer temp = Integer.valueOf(oldCode.substring(oldCode.length()-2, oldCode.length())) ;
                temp=temp+1;
                String nums = new DecimalFormat("00").format(temp);
                code=productcode+yearMonth+nums;
            }else{
                code=productcode+yearMonth+"00";
            }
            code.trim();
            jqylMaterialdetail.setCode(code);
        }
        jqylMaterialdetail.setBatchnums(jqylMaterial.getBatchnums());
        jqylMaterialdetail.setName(jqylMaterial.getResourcename());
        jqylMaterialdetail.setOutstorageaddtime(new Date());
        jqylMaterialdetail.setUnit(jqylMaterial.getUnit());
        jqylMaterialdetail.setTypenums(jqylMaterial.getTypenums());
        jqylMaterialdetail.setIsrepair(0);
        boolean insert = super.insert(jqylMaterialdetail);
        return insert;
    }

    @Override
    public MaterialCheck selectUnqualifiedMaterialCheck(String id) {
        MaterialCheck materialCheck =new MaterialCheck();
        JqylMaterialdetail jqylMaterialdetail = super.selectById(id);

        //部件
        if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterialdetail.getPid(),null)){
            materialCheck.setCode(jqylMaterialdetail.getPcode());
            materialCheck.setType("部装记录");
            //根据pid查找到检测记录
            Wrapper<JqbzMaterialListCheck> wrapper =new EntityWrapper<>();
            wrapper.eq("pid",jqylMaterialdetail.getPid());
            List<JqbzMaterialListCheck> jqbzMaterialListChecks = jqbzMaterialListCheckMapper.selectList(wrapper);
            if (jqbzMaterialListChecks!=null && jqbzMaterialListChecks.size()>0){
                for (JqbzMaterialListCheck materialListCheck : jqbzMaterialListChecks) {
                    JyUser jyUser = jyUserMapper.selectById(materialListCheck.getCreator());
                    if (AdscmBaseUtils.getInstance().isNotEmpty(jyUser,null)){
                        materialListCheck.setCreatorName(jyUser.getName());
                    }
                }
                materialCheck.setJqbzMaterialListCheck(jqbzMaterialListChecks);
            }

        }else {
            //总装
            materialCheck.setCode(jqylMaterialdetail.getMcode());
            materialCheck.setType("总装记录");
            //跟mid 查找到对应的检测记录
            Wrapper<JqzzMaterialListCheck> wrapper = new EntityWrapper<>();
            wrapper.eq("pid",jqylMaterialdetail.getMid());
            List<JqzzMaterialListCheck> jqzzMaterialListChecks = jqzzMaterialListCheckMapper.selectList(wrapper);
            if (jqzzMaterialListChecks!=null && jqzzMaterialListChecks.size()>0 ){
                for (JqzzMaterialListCheck jqzzMaterialListCheck : jqzzMaterialListChecks) {
                    JyUser jyUser = jyUserMapper.selectById(jqzzMaterialListCheck.getCreator());
                    if (AdscmBaseUtils.getInstance().isNotEmpty(jyUser,null)){
                        jqzzMaterialListCheck.setCreatorName(jyUser.getName());
                    }
                }
                materialCheck.setJqzzMaterialListCheck(jqzzMaterialListChecks);
            }
        }
        return  materialCheck;
    }

    /**
     * 查询未处理的不合格品
     * @return
     */
    @Override
    public List<JqylMaterialdetail> selectUnDeal() {
        Wrapper<JqylMaterialdetail> wrapper =new EntityWrapper<>();
        wrapper.isNull("result");
        wrapper.eq("MATERIALSTATE" ,"0");
        List<JqylMaterialdetail> jqylMaterialdetails = super.selectList(wrapper);
        for (JqylMaterialdetail jqylMaterialdetail : jqylMaterialdetails) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterialdetail.getUseperson(),null)){
                JyUser jyUser = jyUserMapper.selectById(jqylMaterialdetail.getUseperson());
                jqylMaterialdetail.setUsepersonName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterialdetail.getCreator(),null)){
                JyUser jyUser = jyUserMapper.selectById(jqylMaterialdetail.getCreator());
                jqylMaterialdetail.setCreatorName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterialdetail.getName(),null)){
                CgMaterial cgMaterial = cgMaterialMapper.selectById(jqylMaterialdetail.getName());
                if(AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial,null)){
                    jqylMaterialdetail.setNameName(cgMaterial.getName());
                }
                //查询是否已经付款了
                JqylMaterial jqylMaterial = jqylMaterialMapper.selectById(jqylMaterialdetail.getTid());
                Wrapper<CgTask> cgTaskWrapper=new EntityWrapper<>();
                cgTaskWrapper.eq("make_no",jqylMaterial.getTaskcode());
                cgTaskWrapper.eq("supplier",jqylMaterial.getBusinesstype());
                List<CgTask> cgTasks = cgTaskMapper.selectList(cgTaskWrapper);
                if (cgTasks!=null &&cgTasks.size()>0){
                    CgTask cgTask = cgTasks.get(0);
                    jqylMaterialdetail.setIsrepair(cgTask.getIsPay());
                }
            }
            DecimalFormat df=new DecimalFormat("#0.00");
            String format = df.format(jqylMaterialdetail.getUsenums());
            jqylMaterialdetail.setUsenums(Double.valueOf(format));
        }
        return jqylMaterialdetails;
    }

    /**
     * 查询已处理的不合格品
     * @return
     */
    @Override
    public List<JqylMaterialdetail> selectDeal() {
        Wrapper<JqylMaterialdetail> wrapper =new EntityWrapper<>();
        wrapper.isNotNull("result");
        wrapper.eq("MATERIALSTATE" ,"0");
        List<JqylMaterialdetail> jqylMaterialdetails = super.selectList(wrapper);
        for (JqylMaterialdetail jqylMaterialdetail : jqylMaterialdetails) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterialdetail.getUseperson(),null)){
                JyUser jyUser = jyUserMapper.selectById(jqylMaterialdetail.getUseperson());
                jqylMaterialdetail.setUsepersonName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterialdetail.getCreator(),null)){
                JyUser jyUser = jyUserMapper.selectById(jqylMaterialdetail.getCreator());
                jqylMaterialdetail.setCreatorName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterialdetail.getName(),null)){
                CgMaterial cgMaterial = cgMaterialMapper.selectById(jqylMaterialdetail.getName());
                jqylMaterialdetail.setNameName(cgMaterial.getName());
            }
            //查询是否已经付款了
            JqylMaterial jqylMaterial = jqylMaterialMapper.selectById(jqylMaterialdetail.getTid());
            Wrapper<CgTask> cgTaskWrapper=new EntityWrapper<>();
            cgTaskWrapper.eq("make_no",jqylMaterial.getTaskcode());
            cgTaskWrapper.eq("supplier",jqylMaterial.getBusinesstype());
            List<CgTask> cgTasks = cgTaskMapper.selectList(cgTaskWrapper);
            if (cgTasks!=null &&cgTasks.size()>0){
                CgTask cgTask = cgTasks.get(0);
                jqylMaterialdetail.setIsrepair(cgTask.getIsPay());
            }
            DecimalFormat df=new DecimalFormat("#0.00");
            String format = df.format(jqylMaterialdetail.getUsenums());
            jqylMaterialdetail.setUsenums(Double.valueOf(format));
        }
        return jqylMaterialdetails;
    }

    @Override
    public Boolean updateUnqualified(JqylMaterialdetail jqylMaterialdetail) throws AdscmSystemException{
        //先查询查询原有记录
        JqylMaterialdetail oldjqylMaterialdetail = super.selectById(jqylMaterialdetail.getId());

        if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterialdetail.getIsCame(),null)){
             if (!AdscmBaseUtils.getInstance().isNotEmpty(oldjqylMaterialdetail.getIsCame(),null)){
                 if (jqylMaterialdetail.getIsCame()==1){
                     jqylMaterialdetailApproveService.insertJqylMaterialdetailApprove(jqylMaterialdetail);
                 }
             }
        }
        //根据结果处理如果是返回就在原料库里添加一个库存
        if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterialdetail.getResult(),null)){
            if (!AdscmBaseUtils.getInstance().isNotEmpty(oldjqylMaterialdetail.getResult(),null)){
                if (jqylMaterialdetail.getResult()==1){
                    jqylMaterialService.updateJqylMaterialyValue( jqylMaterialdetail.getTid(),jqylMaterialdetail.getUsenums().floatValue());
                }

            }
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterialdetail.getResult(),null)){
            if (!AdscmBaseUtils.getInstance().isNotEmpty(oldjqylMaterialdetail.getResult(),null)){
                if (jqylMaterialdetail.getResult()==0){
                    JqylMaterialdetailReback jqylMaterialdetailReback =new JqylMaterialdetailReback();
                    jqylMaterialdetailReback.setState(0);
                    jqylMaterialdetailReback.setTid(jqylMaterialdetail.getId());
                    jqylMaterialdetailRebackMapper.insert(jqylMaterialdetailReback);
                }
            }
        }


        super.updateById(jqylMaterialdetail);
        return true;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean jqylMaterialdetailToShylMaterial(JqylMaterialdetail jqylMaterialdetail, Token token) throws AdscmSystemException{

        JqylMaterial jqylMaterial = jqylMaterialMapper.selectById(jqylMaterialdetail.getTid());
        CgMaterial cgMaterial = cgMaterialMapper.selectById(jqylMaterial.getResourcename());
        if (cgMaterial.getRemaining()==0){
            throw new AdscmSystemException("不可以转移，无多余量");
        }
        if (jqylMaterialdetail.getUsenums()>cgMaterial.getRemaining()){
            throw new AdscmSystemException("使用量大于了转移量，无多余量");
        }
        ShylMaterial shylMaterial =new ShylMaterial();
        shylMaterial.setTasknums( Double.valueOf(jqylMaterial.getTasknums()));
        shylMaterial.setBatchnums(new SimpleDateFormat("yyMMdd").format(new Date()));
        shylMaterial.setResourcename(jqylMaterial.getResourcename());
        shylMaterial.setTypenums(cgMaterial.getType());
        shylMaterial.setTaskreleaseperson(token.getUser().getId().toString());
        shylMaterial.setTaskreleaseaddtime(new Date());
        shylMaterial.setTaskperformperson(token.getUser().getId().toString());
        //计划到达时间
        shylMaterial.setTaskstartorendtime(jqylMaterial.getTaskstartorendtime());
        //启动任务
        shylMaterial.setIstaskstart(1);
        shylMaterial.setTaskstartaddtime(new Date());
        //已经收货
        shylMaterial.setIstaskbegin(1);
        //实际收货时间
        shylMaterial.setTaskbegintime(new Date());
        shylMaterial.setTaskbeginaddtime(new Date());
        shylMaterial.setTaskfinishstate(0);
        shylMaterial.setTaskstate(0);
        shylMaterial.setTasknums(jqylMaterialdetail.getUsenums());
        shylMaterial.setActualcompletenums(jqylMaterialdetail.getUsenums());
        shylMaterial.setRemainingnums(jqylMaterialdetail.getUsenums());
        shylMaterial.setIstaskend(0);
        shylMaterial.setIsreviewtask(0);
        shylMaterial.setReviewresult(-1);
        shylMaterial.setTaskstate(1);
        shylMaterial.setPrice(jqylMaterial.getPrice());
        shylMaterial.setTotals(jqylMaterial.getPrice()* jqylMaterialdetail.getUsenums().floatValue());
        shylMaterial.setBusinesstype(jqylMaterial.getBusinesstype());
        cgMaterial.setRemaining(cgMaterial.getRemaining()-jqylMaterialdetail.getUsenums().floatValue());
        cgMaterialMapper.updateById(cgMaterial);
        shylMaterialMapper.insert(shylMaterial);
        jqylMaterialdetail.setName(cgMaterial.getId().toString());
        jqylMaterialdetail.setCode(cgMaterial.getCode());
        jqylMaterialdetail.setTypenums(cgMaterial.getType());
        jqylMaterialdetail.setMaterialstate("1");
        jqylMaterialdetail.setOutstoragetime(new Date());
        jqylMaterialdetail.setCreator(token.getUser().getId().toString());
        jqylMaterialdetail.setCreaeTime(new Date());
        super.insert(jqylMaterialdetail);

        return true;
    }

}

